<?php

class Mac_Db_Connection
{
    protected static $connection = null;
    
    protected static $host;
    protected static $user;
    protected static $pass;
    protected static $name;
    
    protected static $debugmode = false;
    
    protected $result;
    
    /**
     * @var Database_Mysql
     */
    private static $instance = null;
    
    /**
     * Renvoie une instance de la BDD
     * @param string $dbname
     * @return Database_Mysql
     */
    public static function connect ($dbname = null)
    {
        if (self::$instance === null) {
            self::$instance = new self();
            self::$instance->dbConnect($dbname);
        }
        return self::$instance;
    }
    
    /**
     * Configuration
     *
     * @param string $_host Database hostname
     * @param string $_user Database user name
     * @param string $_pass Database password
     * @param string $_db   Database name
     */
    public static function configure ($_host, $_user, $_pass, $_db = null)
    {
        self::$host = $_host;
        self::$user = $_user;
        self::$pass = $_pass;
        self::$name = $_db;
    }
    
    /**
     * Constructor
     */
    private function __construct ()
    {}
    
    /**
     * Destructor
     */
    public function __destruct ()
    {
        $this->dbDisconnect();
    }
    
    /**
     * Create connection to database
     *
     * @param string $_host Database hostname
     * @param string $_name Database name
     * @param string $_user Database user name
     * @param string $_pass Database password
     */
    protected function dbConnect ($dbname = null)
    {
        if ($dbname !== null) {
            self::$name = $dbname;
        }
        if (!$connection = mysql_connect(self::$host, self::$user, self::$pass)) {
            throw new Mac_Db_Exception_Connection("Connexion impossible au serveur : ".$host);
        } else {
            self::$connection = $connection;
            if (self::$name !== null) {
                if (!mysql_select_db(self::$name, self::$connection)) {
                    throw new Mac_Db_Exception_Connection("Impossible de selectionner la base : ".$dbname);
                } else {
                    mysql_query('SET NAMES UTF8');
                    mysql_set_charset('utf-8');
                }
            }
        }
    }
    
    /**
     * Disconnect to database
     */
    protected function dbDisconnect ()
    {
        if (!mysql_close(self::$connection)) {
            throw new Mac_Db_Exception_Connection("Deconnexion impossible");
        }
        self::$connection = null;
    }
    
    public static function dbSelect ($dbname)
    {
        self::$name = $dbname;
    }
    
    public static function executeQuery ($query)
    {
        return mysql_query($query, self::$connection);
    }
    
    public static function getLastError ()
    {
        return mysql_error(self::$connection);
    }
}